﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using BizElements.TemplateEngine;

namespace BizElements.Generator
{
    static class TemplateUtil
    {
        public static IList<TemplateComponentVariableDefinition> GetApplicableComponentVariables(ITemplateInputComponent component, IEnumerable<ITemplate> allTemplates)
        {
            List<TemplateComponentVariableDefinition> applicableComponentVariables = new List<TemplateComponentVariableDefinition>();
            foreach (ITemplate template in allTemplates)
            {
                foreach (TemplateComponentVariableDefinition componentVar in template.GetComponentVariablesUsedFor(component))
                {
                    bool isNew = !applicableComponentVariables.Exists((existing) => (existing.Name == componentVar.Name));
                    if (isNew)
                        applicableComponentVariables.Add(componentVar);
                }
            }

            return applicableComponentVariables;
        }

        public static IList<TemplateComponentVariableDefinition> GetApplicableComponentVariablesForChildren(ITemplateInputComponent parentComponent, ComponentType subcomponentType, IEnumerable<ITemplate> allTemplates)
        {
            ITemplateInputComponent childComponent = parentComponent.GetChildren(subcomponentType).FirstOrDefault();
            if (childComponent == null)
                return new List<TemplateComponentVariableDefinition>();

            List<TemplateComponentVariableDefinition> applicableComponentVariables = new List<TemplateComponentVariableDefinition>();
            foreach (ITemplate template in allTemplates)
            {
                foreach (TemplateComponentVariableDefinition componentVar in template.GetComponentVariablesUsedFor(childComponent))
                {
                    bool isNew = !applicableComponentVariables.Exists((existing) => (existing.Name == componentVar.Name));
                    if (isNew)
                        applicableComponentVariables.Add(componentVar);
                }
            }

            return applicableComponentVariables;
        }

        public static List<Pair<string, string>> GetComponentVariableValues(IDictionary<string, IDictionary<string, string>> allComponentVariables, string componentName)
        {
            List<Pair<string, string>> currentValues = new List<Pair<string, string>>();
            IDictionary<string, string> componentVariables;
            allComponentVariables.TryGetValue(componentName, out componentVariables);
            if (componentVariables == null)
                return currentValues;

            foreach (KeyValuePair<string, string> nameAndValue in componentVariables)
                currentValues.Add(new Pair<string, string>(nameAndValue.Key, nameAndValue.Value));

            return currentValues;
        }
    }
}
